package com.zoweunion.mechanic.service.base.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.entity.CarListBean;
import com.zoweunion.mechanic.entity.FacilitatorEntity;
import com.zoweunion.mechanic.model.things.ThingsData;
import com.zoweunion.mechanic.plugins.mq.RabbitMQCustomer;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.base.LockCarMapper;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.app.ToolCarDataService;
import com.zoweunion.mechanic.service.base.OwnerService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.cache.ThingsCacheUtil;
import com.zoweunion.mechanic.util.common.CarDataStatisticsUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 车主管理业务类
 * 
 * @author Administrator
 *
 */
@Service
@Transactional
@SuppressWarnings("unchecked")
public class OwnerServiceImpl extends BaseService implements OwnerService {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OwnerDao ownerDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private AppDao appDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private LockCarMapper lockCarMapper;
	@Autowired
	private ToolCarDataService toolCarDataService;
	@Autowired
	private ToolCarDataMapper toolCarDataMapper;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ThingsCacheUtil thingsCacheUtil;
	@Autowired
	private RabbitMQCustomer rabbitMQCustomer;

	@Autowired
	private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;

	@Autowired
	private UserService userService;

	@Override
    @Transactional(rollbackFor = Exception.class)
	public int addCar(Map<String, Object> reqMap) throws MyException{
	    //品牌型号情况下，获取机型，未做父级品牌判断，此种情况默认前端必传父级品牌
        if ((!reqMap.containsKey("car_type_id") || Orgin.getString(reqMap, "car_type_id").equals("")) || null == Orgin.getString(reqMap, "car_type_id")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String typeId = ownerDao.getTypeIdByBrandId(reqMap);
                reqMap.put("car_type_id", typeId);
            }
        }
        //大类情况下，获取父级品牌，未做机型判断，此种情况默认前端必传机型
        if ((!reqMap.containsKey("car_brand_parent_id") || Orgin.getString(reqMap, "car_brand_parent_id").equals("")) || null == Orgin.getString(reqMap, "car_brand_parent_id")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String brandParentId = ownerDao.getBrandParentIdByBrandId(reqMap);
                reqMap.put("car_brand_parent_id", brandParentId);
            }
        }
        //品牌型号情况下，获取机型，未做父级品牌判断，此种情况默认前端必传父级品牌-------这是存名称
        if ((!reqMap.containsKey("car_type") || Orgin.getString(reqMap, "car_type").equals("")) || null == Orgin.getString(reqMap, "car_type")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String Type = ownerDao.getTypeByBrandId(reqMap);
                reqMap.put("car_type", Type);
            }
        }

		String thingsId = reqMap.get("things_id").toString();
        if(!thingsId.equals("")) {
			int selectThingsId = ownerDao.selectThingsId(thingsId);
			if (selectThingsId > 1) {
				throw new MyException(Constants.CODE_HANDEL_FAILED, "该物联网号编号已被绑定");
			}
		}

		//isExcavator 非挖机0 挖机1
		if(reqMap.containsKey("isExcavator")&&Orgin.getIntValue(reqMap,"isExcavator")==0){
		    //如果表中已有thing_id则不添加
		    Integer i = ownerDao.getExcavator(reqMap.get("things_id").toString());
		    if (i == 0) {
                ownerDao.insertExcavator(thingsId);
            }
		}
		int result = 0;
		if (Orgin.getString(reqMap, "id") != null && !Orgin.getString(reqMap, "id").equals("")) {
            reqMap.put("o_id", reqMap.get("id"));// 将传来的车主id保存为o_id
        } else {
		    throw new MyException(Constants.CODE_SUCCESS, "当前车主未选择，请重新添加车辆");
        }
		// 1车辆表插入数据
		if (reqMap.containsKey("c_id")){
			reqMap.put("id", reqMap.get("c_id").toString());
			reqMap.put("is_shipment", 1);
			result += ownerDao.editCar(reqMap);
		}else {
			reqMap.put("id", UuidUtil.get32UUID());// 车辆表主键id
			reqMap.put("is_shipment", 1);
			//将传过来的type_id brand_id model_id转成name
			//this.getTypeName(reqMap,false);
			result += ownerDao.addCar(reqMap);
		}
		// 2车主_车辆关联插入数据
		reqMap.put("c_id", reqMap.get("id"));// 将车辆id 保存为c_id
		reqMap.put("id", UuidUtil.get32UUID()); // 关联表的id
		result += ownerDao.addOwnerCar(reqMap);

		// 3将关联的物联网卡设置为已绑定
		reqMap.put("register_type", 0);
		result += ownerDao.updateThings(reqMap);
		try {
			if (result > 0) {
				Map<String, Object> carMap = facilitatorPersonnelRelationDao.selectCar(Orgin.getString(reqMap, "c_id"));
				reqMap.put("car_name", Orgin.getString(carMap, "advice_name"));
				Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
				reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
				//日志系统操作记录-车辆管理_新增
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车辆管理"), Constants.OperationType.getOperationTypeCode("新增"),
						Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
						Orgin.getString(reqMap, "c_id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	public int unbind(Map<String, Object> reqMap) {
		int result = 0;
		// 1车主车辆解绑
		result += ownerDao.deleteOwnerCar(reqMap);
		//根据车辆id 查询本服务商所有的绑定信息
		List<Map<String, Object>> ownerCars = ownerDao.getOwnerCarByCarId(reqMap);
		if (ownerCars.size() == 0) {
			// 2删除车辆
			result += ownerDao.deleteCar(reqMap);
			// 3解绑物联网卡
			reqMap.put("register_type", 1);
			result += ownerDao.updateThings(reqMap);
		}
		return result;
	}

	@Override
	public int editCar(Map<String, Object> reqMap) {
        //品牌型号情况下，获取机型，未做父级品牌判断，此种情况默认前端必传父级品牌
        if ((!reqMap.containsKey("car_type_id") || Orgin.getString(reqMap, "car_type_id").equals("")) || null == Orgin.getString(reqMap, "car_type_id")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String typeId = ownerDao.getTypeIdByBrandId(reqMap);
                reqMap.put("car_type_id", typeId);
            }
        }
        //大类情况下，获取父级品牌，未做机型判断，此种情况默认前端必传机型
        if ((!reqMap.containsKey("car_brand_parent_id") || Orgin.getString(reqMap, "car_brand_parent_id").equals("")) || null == Orgin.getString(reqMap, "car_brand_parent_id")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String brandParentId = ownerDao.getBrandParentIdByBrandId(reqMap);
                reqMap.put("car_brand_parent_id", brandParentId);
            }
        }
        //品牌型号情况下，获取机型，未做父级品牌判断，此种情况默认前端必传父级品牌-----保存的是名称
        if ((!reqMap.containsKey("car_type") || Orgin.getString(reqMap, "car_type").equals("")) || null == Orgin.getString(reqMap, "car_type")){
            if ((reqMap.containsKey("car_brand_id") && null != Orgin.getString(reqMap, "car_brand_id"))) {
                String Type = ownerDao.getTypeByBrandId(reqMap);
                reqMap.put("car_type", Type);
            }
        }
		int result = 0;

		// 查询原汽车信息
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("id",reqMap.get("id"));
		Map<String, Object> oldCarInfo = ownerDao.getCarInfoById(paramMap);
		// 1更新车辆信息
		//将传过来的type_id brand_id model_id转成name
		//this.getTypeName(reqMap,false);
		result += ownerDao.editCar(reqMap);

		// 判断是否改变了物联网卡
		if (!reqMap.get("things_id").equals(oldCarInfo.get("things_id"))) {
			// 2解绑原物联网卡
			oldCarInfo.put("register_type", 1);
			result += ownerDao.updateThings(oldCarInfo);

			// 3绑定现有物联网卡
			reqMap.put("register_type", 0);
			result += ownerDao.updateThings(reqMap);
		}

		//isExcavator 非挖机0 挖机1
		if(reqMap.containsKey("isExcavator")&&Orgin.getIntValue(reqMap,"isExcavator")==0){
		    int i = ownerDao.getExcavator(reqMap.get("things_id").toString());
		    if (i == 0) {
                ownerDao.insertExcavator(reqMap.get("things_id").toString());
            }
		} else {
			ownerDao.updateExcavator(reqMap.get("things_id").toString());
		}
		try {
			if (result > 0) {
				Map<String, Object> carMap = facilitatorPersonnelRelationDao.selectCar(Orgin.getString(reqMap, "id"));
				reqMap.put("car_name", Orgin.getString(carMap, "advice_name"));
				Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
				reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
				//日志系统操作记录-车辆管理_编辑
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车辆管理"), Constants.OperationType.getOperationTypeCode("编辑"),
						Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
						Orgin.getString(reqMap, "id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public Map<String, Object> getPageQuery(Map<String, Object> reqMap) {
		// 1.根据s_id,r_id 分页和条件所有车主
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		int limit = Integer.valueOf(pageMap.get("limit").toString());
		reqMap.put("r_id", Constants.ROLE_CZ);
		int sType = toolCarDataMapper.selectIsServer(Orgin.getString(reqMap, "s_id"));
		if (sType == 1 && reqMap.containsKey("subSid")) {
			reqMap.put("s_id", Orgin.getString(reqMap, "subSid"));
		}
		List<Map<String, Object>> ownerList = new ArrayList<>();
		//sType == 4 则为金融平台账户，需要查询账户下所有的服务商和子服务商的车主
		if(sType == 4){
			ownerList = ownerDao.pageQueryByBanking(reqMap);
		}else {
			//sType == 1\2\3
			ownerList = ownerDao.pageQuery(reqMap);
		}
		//查询用户使用和还款的详情
		if (reqMap.get("creditLimit") != null) {

			if (reqMap.get("creditLimit").equals("1")) {

				for (Map<String,Object> ownerMap : ownerList) {

					// 获取用户还款总额度
					Double orderRepaymentSum = 0.0;
					// 获取用户使用总额度
					Double orderUseSum = 0.0;

					if (orderDao.getOrderRepaymentSum(ownerMap) != null) {

						orderRepaymentSum = Math.ceil(orderDao.getOrderRepaymentSum(ownerMap));
					}

					if (orderDao.getOrderUseSum(ownerMap) != null) {

						orderUseSum = Math.ceil(orderDao.getOrderUseSum(ownerMap));
					}

					ownerMap.put("orderRepaymentSum",orderRepaymentSum);
					ownerMap.put("orderUseSum",orderUseSum);
				}
			}
		}

		// 2.遍历集合,根据车主id 关联查询车主所拥有的车数量 然后插入到车主数据中
		for (Map<String, Object> map : ownerList) {
			int count = ownerDao.countCarsByOid(map.get("id").toString());
			map.put("carNumber", count);
		}

		// 3查询总记录数
		int total = 0;
		if(sType == 4) {
			total = ownerDao.countOwnerByBanking(reqMap);
		}else{
			total = ownerDao.countOwner(reqMap);
		}
		// 4包装结果集 总条数 总页数 数据集
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int pages = (total + limit - 1) / limit;// 总页数 需要有余进一

		resultMap.put("total", total);
		resultMap.put("pages", pages);
		resultMap.put("list", ownerList);
		return resultMap;
	}

    @Override
    public List<FacilitatorEntity> getFacilitatorList(Map<String, Object> reqMap) {
		List<FacilitatorEntity> facilitators = ownerDao.getFacilitatorList(reqMap);
		if (facilitators.size() > 0) {
			Map<String, Object> hashMap = new HashMap<>();
			for (int i = 0; i < facilitators.size() ; i++) {
				String id = facilitators.get(i).getId();
				int serverType = facilitators.get(i).getServerType();
				if(!id.isEmpty() && serverType == 1 ) {
					hashMap.put("server_type", 2);
					hashMap.put("p_id", id);
					List<FacilitatorEntity> childList = getFacilitatorList(hashMap);
					facilitators.get(i).setChildList(childList);
				}
			}
		}
		return facilitators;
    }

    @Override
	public List<Map<String, Object>> getCarsByOid(Map<String, Object> reqMap) {
		List<Map<String,Object>> list = ownerDao.getCarsByOid(reqMap);
//		for (Map<String,Object> map:list){
//			this.getTypeName(map,true);
//		}
		return list;
	}

	private void getTypeName(Map<String, Object> map,boolean isList) {
		if(map.get("car_type_id")!=null && !map.get("car_type_id").toString().isEmpty()){
			String carTypeId = map.get("car_type_id").toString();
			String sonTypeId = carTypeId;
			if(carTypeId.contains("/")){
				sonTypeId = carTypeId.split("/")[1];
			}
			List<String> carTypeList = new ArrayList<>();
			List<String> carTypeIdList = new ArrayList<>();
			Map<String,Object> carType = ownerDao.getCarTypeById(sonTypeId,"t_s_ss_vehicle_type");
			if(carType.get("parent_id")!=null && !carType.get("parent_id").toString().isEmpty()){
				String carTypeParent = ownerDao.getCarTypeById(carType.get("parent_id").toString(),"t_s_ss_vehicle_type").get("type_name").toString();
				carTypeList.add(carTypeParent);
				//carTypeIdList.add(carType.get("parent_id").toString());
			}
			carTypeList.add(carType.get("type_name").toString());
			carTypeIdList.add(map.get("car_type_id").toString());
			map.put("car_type",String.join("/",carTypeList));
			map.put("car_type_id",String.join("/",carTypeIdList));
		}
		if(map.get("car_brand_id")!=null && !map.get("car_brand_id").toString().isEmpty()){
			String carBrand = ownerDao.getCarTypeById(map.get("car_brand_id").toString(),"t_s_ss_vehicle_brand").get("brand_name").toString();
			map.put("brand",carBrand);
		}
		if(map.get("car_model_id")!=null && !map.get("car_model_id").toString().isEmpty()){
			String carModel = ownerDao.getCarTypeById(map.get("car_model_id").toString(),"t_s_ss_vehicle_model").get("model_name").toString();
			map.put("model",carModel);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public Map<String, Object> getThingsList(Map<String, Object> reqMap) {
		// 1.设置分页的limit和offset
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		int limit = Integer.valueOf(pageMap.get("limit").toString());
		// 2.查询总记录数
		int total = ownerDao.CountUnbindThings(reqMap);
		// 3执行分页查询
		List<Map<String, Object>> list = ownerDao.getUnbindThingsList(reqMap);

		// 4包装结果集 总条数 总页数 数据集
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		int pages = (total + limit - 1) / limit;// 总页数 需要有余进一

		resultMap.put("total", total);
		resultMap.put("pages", pages);
		resultMap.put("list", list);
		return resultMap;
	}

	@Override
	public int deleteOwner(Map<String, Object> reqMap) throws MyException {
		int result = 0;
		String r_id = Orgin.getString(userService.getUserById(Orgin.getString(reqMap, "id")), "r_id");
		Map<String, Object> ownerMap = userDao.getUserById(Orgin.getString(reqMap, "id"));
		reqMap.put("operated_person_name", Orgin.getString(ownerMap, "user_name"));
		// 1根据车主id查询车主的所有车辆
		reqMap.put("o_id", reqMap.get("id").toString());
		//根据车主id进行查询需要排除掉user_name;这里的user_name为服务商的用户名，而不是车主的user_name，在这里不需要
		reqMap.remove("user_name");
		List<Map<String, Object>> carList = ownerDao.getCarsByOid(reqMap);
		if (carList != null && carList.size()>=1 ) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请解绑车主名下车辆后，再删除车主");
		}
		// 删除车辆车主关联表
		Optional.ofNullable(carList).ifPresent(x -> x.forEach(carMap -> {
			carMap.put("update_user", reqMap.get("current_user_id").toString());
			carMap.put("o_id", reqMap.get("o_id").toString());
			ownerDao.deleteOwnerCar(carMap);
		}));
		// 根据车辆id删除车辆
		// 根据things_id解绑物联网卡
		Optional.ofNullable(carList).ifPresent(x -> x.forEach(carMap -> {
			carMap.put("s_id", reqMap.get("s_id").toString());
			//根据车辆id 查询本服务商所有的绑定信息
			List<Map<String, Object>> ownerCars = ownerDao.getOwnerCarByCarId(carMap);
			if (ownerCars.size() == 0) {
				carMap.put("update_user", reqMap.get("current_user_id").toString());
				carMap.put("register_type", 1);
				ownerDao.updateThings(carMap);
				ownerDao.deleteCar(carMap);
			}
		}));
		// 4.删除车主
		result += ownerDao.deleteOwner(reqMap);
		try {
			Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
			reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
			if (result > 0) {
				if (r_id.equals(Constants.ROLE_CZ)) {
					//日志系统操作记录-车主管理-删除
					rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("删除"),
					Orgin.getString(reqMap, "current_user_id"), Orgin.getString(reqMap, "user_name"),
							Orgin.getString(reqMap, "id"), Orgin.getString(reqMap, "operated_person_name"), "", "", Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
				} else {
					//日志系统操作记录-人员管理-删除
					rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("删除"),
					Orgin.getString(reqMap, "current_user_id"), Orgin.getString(reqMap, "user_name"),
							Orgin.getString(reqMap, "id"), Orgin.getString(reqMap, "operated_person_name"), "", "", Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	public Map<String, Object> getOneCarLocation(Map<String, Object> reqMap) {
		// 1根据s_id查询服务商信息
		Map<String, Object> serverInfo = userDao.getServerInfoBySId(reqMap);

		// 2调用物联网卡地址接口查询信息
		String thingsInfo = HttpClient.doGet(Constants.THINGS_URL_ONE + reqMap.get("opc_path"),
				serverInfo.get("interface_account") + "", serverInfo.get("unify_account") + "");

		// 3取出经纬度信息 并返回
		JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
		JSONObject thingsObject = (JSONObject) thingsArray.get(0);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("id", reqMap.get("id"));
		if (thingsObject != null) {
			List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject.get("OPCValueList");
			if (OPCValueList != null && OPCValueList.size() > 0) {
				for (Map<String, Object> OPCValue : OPCValueList) {
					if (OPCValue.get("ValueTag").equals("GPSlongitude")) {// 经度
						resultMap.put("GPSlongitude", OPCValue.get("DataValue"));
					}
					if (OPCValue.get("ValueTag").equals("GPSlatitude")) {// 纬度
						resultMap.put("GPSlatitude", OPCValue.get("DataValue"));
					}
				}
			}
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> getOneCarLocationNew(Map<String, Object> reqMap) throws MyException {
		// 1根据s_id查询服务商信息
		Map<String, Object> serverInfo = userDao.getServerInfoBySId(reqMap);

		String thingsId = reqMap.get("opc_path").toString();
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String adviceTemplateId = pcCarMap.get("device_template").toString();
		String tableName = ThingsData.getTableName(adviceTemplateId);
		// 获取车辆最新设备信息
		Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, thingsId);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("id", reqMap.get("id"));
		resultMap.put("GPSlongitude", carDataMap.get("GPSlongitude"));
		resultMap.put("GPSlatitude", carDataMap.get("GPSlatitude"));
		return resultMap;
	}

	@Override
	public List<Map<String, Object>> getAllCarList(Map<String, Object> reqMap) {
		// 1根据s_id查询服务商信息
		Map<String, Object> serverInfo = userDao.getServerInfoBySId(reqMap);
		// 设置分页
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		// 2根据s_id查询该服务上下所有车辆
		List<Map<String, Object>> carsList = ownerDao.getCarsListBySId(reqMap);
		return carsList;
	}

	@Override
	public List<Map<String, Object>> getAllCarLocation(Map<String, Object> reqMap) {

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();// 创建一个保存数据的结果集list

		// 1根据s_id查询服务商信息
		Map<String, Object> serverInfo = userDao.getServerInfoBySId(reqMap);
		// 2根据s_id查询该服务上下所有车辆
		List<Map<String, Object>> carsList = ownerDao.getCarsBySId(reqMap);

		// 定义循环标志
		int i = 0;
		if (carsList != null && carsList.size() > 0) {
			for (Map<String, Object> carMap : carsList) {
				StringBuffer locations = new StringBuffer();

				// 调用物联网卡地址接口查询信息
				String thingsInfo = HttpClient.doGet(Constants.THINGS_URL_ONE + carMap.get("opc_path"),
						serverInfo.get("interface_account") + "", serverInfo.get("unify_account") + "");
				// 取出经纬度信息 并返回
				JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
				Map<String, Object> resultMap = new HashMap<String, Object>(); // 创建一个保存车辆位置的map
				if (thingsArray.size() > 0) { // 防止查不到数据
					resultMap.put("id", carMap.get("id")); // 添加车辆id
					resultMap.put("car_type", carMap.get("car_type"));
					resultMap.put("things_id", carMap.get("things_id"));
					resultMap.put("car_no", carMap.get("car_no"));
					JSONObject thingsObject = (JSONObject) thingsArray.get(0);
					if (thingsObject != null) {
						List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject
								.get("OPCValueList");
						if (OPCValueList != null && OPCValueList.size() > 0) {
							for (Map<String, Object> OPCValue : OPCValueList) {
								if (OPCValue.get("ValueTag").equals("GPSlongitude")) {
									resultMap.put("GPSlongitude", OPCValue.get("DataValue"));// 添加经度
								}
								if (OPCValue.get("ValueTag").equals("GPSlatitude")) {// 纬度
									resultMap.put("GPSlatitude", OPCValue.get("DataValue"));// 添加纬度
								}
								if (OPCValue.get("ValueTag").equals("OperatingHours")) {
									//新思联车辆运行小时 加上数据库 的车辆运行小时
									BigDecimal bigDecimal = new BigDecimal(carMap.get("running").toString());
									BigDecimal bigDecimalAdd = bigDecimal.add(new BigDecimal(OPCValue.get("DataValue").toString()));
									resultMap.put("running", bigDecimalAdd.setScale(1, BigDecimal.ROUND_HALF_UP));
								}
							}
							// 将GPS定位转换成高德定位
							double[] doubles = GPSUtil.gps84_To_Gcj02(
									Double.valueOf(resultMap.get("GPSlatitude").toString()),
									Double.valueOf(resultMap.get("GPSlongitude").toString()));
							if (doubles.length >= 2) {
								// 判断经纬度合不合法
								if ((doubles[0] > 0.06 || doubles[0] < -0.06)
										&& (doubles[1] > 0.06 || doubles[1] < -0.06)) {
									// 如果合法 查询数据库有没有这个车信息 没有则新增 有则更新
									List<Map<String, Object>> carHistoryMap = ownerDao.getCarHistory(carMap);
									if (carHistoryMap.size() > 0) {
										carMap.put("gps_longitude", doubles[1]);
										carMap.put("gps_latitude", doubles[0]);
										ownerDao.updateCarHistory(carMap);
									} else {
										carMap.put("gps_longitude", doubles[1]);
										carMap.put("gps_latitude", doubles[0]);
										carMap.put("car_history_id", UuidUtil.get32UUID());
										ownerDao.createCarHistory(carMap);
									}
									// 更新完 将高德gps存入resultMap
									resultMap.put("GPSlongitude", doubles[1]);
									resultMap.put("GPSlatitude", doubles[0]);
								} else {
									// 不合法 取数据库这辆车的经纬度
									List<Map<String, Object>> carHistoryMapList = ownerDao.getCarHistory(carMap);
									if (carHistoryMapList.size() > 0) {
										Map<String, Object> carHistoryMap = carHistoryMapList.get(0);
										resultMap.put("GPSlongitude", carHistoryMap.get("gps_longitude"));
										resultMap.put("GPSlatitude", carHistoryMap.get("gps_latitude"));
									} else {
										continue;
									}
								}
							}
							/*if (resultMap.containsKey("GPSlongitude") && resultMap.containsKey("GPSlatitude")) {

								if (i < 40) {
									if (i == 39) {

										locations.append(resultMap.get("GPSlongitude").toString() + ","
												+ resultMap.get("GPSlatitude").toString());

									} else {

										locations.append(resultMap.get("GPSlongitude").toString() + ","
												+ resultMap.get("GPSlatitude").toString() + "|");

									}
									i++;
								}

							}*/
						}
					}
					/*if (i == 40) {
						String url = "https://restapi.amap.com/v3/assistant/coordinate/convert?key=e4dff7935045e4aadf06e230816b9fcc&locations="
								+ locations.toString() + "&coordsys=gps&output=json";
						String resultString = restTemplate.getForObject(url, String.class);
						resultMap.put("resultString", resultString);
						i = 0;
					}*/
					resultMap.put("carInfo", thingsArray);
					resultList.add(resultMap); // 添加车辆map
				}

			}
		}

		return resultList;
	}

	@Override
	public Map<String, Object> getAllCarLocationNew(User currentUser, Map<String, Object> reqMap) {
		this.appPage(reqMap);
		reqMap.put("sId", currentUser.getS_id());
		reqMap.put("current_login_user_id", currentUser.getId());
		int count = 0;
		List<Map<String, Object>> carList = new ArrayList<>();
		//金融平台
		if(reqMap.get("server_type") != null && Integer.valueOf(reqMap.get("server_type").toString()) == 4) {
			count = toolCarDataMapper.countBankingListCar(reqMap);
			carList = toolCarDataMapper.bankinglistCar(reqMap);
		}else {
			count = toolCarDataMapper.countListCar(reqMap);
			carList = toolCarDataMapper.listCar(reqMap);
		}
		// 设置状态
		toolCarDataService.setState(carList);
		Map<String, Object> resultMap = new HashMap<>(6);
		resultMap.put("list", carList);
		resultMap.put("count", count);
		resultMap.put("s_id", currentUser.getS_id());
		return resultMap;
	}

	@Override
	public Map<String, Object> getCarRealData(User currentUser, Map<String, Object> reqMap) throws MyException {
		return toolCarDataService.realData(currentUser, reqMap);
	}

	@Override
	public Map<String, Object> getRunningRecordNew(User currentUser, Map<String, Object> reqMap) throws MyException {

		LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString());
		LocalDate endTime = DateUtil.parseDate(reqMap.get("endTime").toString());

		if (startTime.isAfter(endTime)) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "开始时间不能大于结束时间");
		}

		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		reqMap.put("tableName", ThingsData.getTableName(pcCarMap.get("device_template").toString()));
		reqMap.put("sId", currentUser.getS_id());
		reqMap.put("isMax", true);
		List<Map<String, Object>> carDataList = toolCarDataMapper.workingHourStatistics2(reqMap);
		Map<String, Object> resultMap = new HashMap<>(3);
		resultMap.put("list", carDataList);
		return resultMap;
	}

	@Override
	public List<Map<String, Object>> listIndex(User currentUser, Map<String, Object> reqMap) {
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
		String adviceTemplateId = pcCarMap.get("device_template").toString();
		return thingsCacheUtil.getIntelligentTemplateDetails(adviceTemplateId);
	}

	@Override
	public Map<String, Object> carHistoricalDataPCNew(User currentUser, Map<String, Object> reqMap) throws MyException {
		// 分页数据
		this.appPage(reqMap);
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
		if (pcCarMap == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "暂无数据");
		}
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
		reqMap.put("tableName", tableName);
		int count = toolCarDataMapper.countListCarHistoryData(reqMap);
		List<Map<String, Object>> carHistoryDataList = toolCarDataMapper.listCarHistoryData(reqMap);
		// 获取智能模版参数
		LinkedList<Map<String, Object>> intelligentTemplateDetails = thingsCacheUtil.getIntelligentTemplateDetails(pcCarMap.get("device_template").toString());
		CarDataStatisticsUtil.setSampleTimeTag(intelligentTemplateDetails);

		LinkedList<Map<String, Object>> carDataList = new LinkedList<>();
		for (Map<String, Object> carMap : carHistoryDataList) {
			carDataList.addLast(CarDataStatisticsUtil.getCarDatasetUnit(carMap, intelligentTemplateDetails));
		}
		Map<String, Object> resultMap = new HashMap<>(3);
		resultMap.put("dataList", carDataList);
		resultMap.put("dataName", CarDataStatisticsUtil.getDataName(intelligentTemplateDetails));
		resultMap.put("count", count);
		return resultMap;
	}

	@Override
	public Map<String, Object> carHistoricalDataLineNew(User currentUser, Map<String, Object> reqMap) throws MyException {
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
		reqMap.put("tableName", tableName);
		List<Map<String, Object>> carHistoryDataList = toolCarDataMapper.getCarHistoryIndexData(reqMap);
		Map<String, Object> resultMap = new HashMap<>(3);
		resultMap.put("list", carHistoryDataList);
		return resultMap;
	}

	@Override
	public Map<String, Object> getAllCar(Map<String, Object> reqMap) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		List<Map<String, Object>> carsList = new ArrayList<>();
		List<Map<String, Object>> serverList = new ArrayList<>();
		int count = 0;
		//如果server_type==4 则为金融平台，需要查询其创建的所有的服务商以及主机下的服务商
		if(reqMap.get("server_type") != null && Integer.valueOf(reqMap.get("server_type").toString()) == 4){
			carsList = ownerDao.getCarsByBankingIdPage(reqMap);
			serverList = ownerDao.getCarsByBankingIdPageForServerList(reqMap);//added by zhanghongfu
			count = ownerDao.getCarsCountByBankingId(reqMap);
		}else {
			// 2根据s_id查询该服务上下所有车辆
			carsList = ownerDao.getCarsBySIdPage(reqMap);
			count = ownerDao.getCarsBySIdCount(reqMap);
		}
		map.put("carsList", carsList);
		map.put("count", count);
		map.put("s_id", reqMap.get("s_id").toString());
		map.put("serverList", serverList);//added by zhanghongfu
		return map;
	}

	@Override
	public List<Map<String, Object>> getCarsBySid(Map<String, Object> map) {
		List<Map<String, Object>> carsList = ownerDao.getCarsBySId(map);
		return carsList;
	}

	@Override
	public List<Map<String, Object>> getCars(Map<String, Object> reqMap) {
		List<Map<String, Object>> carsList = ownerDao.getCars(reqMap);
		return carsList;
	}

	@Override
	public boolean bindingCar(Map<String, Object> reqMap){
		// 车主_车辆关联插入数据
		reqMap.put("c_id", reqMap.get("id"));// 将车辆id 保存为c_id
		reqMap.put("id", UuidUtil.get32UUID()); // 关联表的id
		return ownerDao.addOwnerCar(reqMap) > 0;
	}

    @Override
    public List<Map<String, Object>> getEngineNameList() {
        List<Map<String, Object>> reqMap = new ArrayList<>();
        reqMap = ownerDao.getEngineNameList();
        return reqMap;
    }

    @Override
    public PageInfo getOwnerList(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = ownerDao.getOwnerList(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public PageInfo getCarsByOidNew(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
		List<Map<String, Object>> list = new ArrayList<>();
		if(reqMap.get("server_type") != null && reqMap.get("server_type").toString().equals("2")){
			list = ownerDao.getCarsByOidNewOfSubService(reqMap);
		}else {
			list = ownerDao.getCarsByOidNew(reqMap);
		}
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(list);
        return mapPageInfo;
    }

    @Override
    public String getFirstBySid(Map<String, Object> reqMap) {
        reqMap.put("r_id", Constants.ROLE_CZ);
        String thingsId = ownerDao.getFirstBySid(reqMap);
        return thingsId;
    }

	@Override
	public void updateCarInfoById(Map<String, Object> reqMap) {
		ownerDao.updateCarInfoById(reqMap);
	}

    @Override
    public List<CarListBean> carsListExport(Map<String, Object> reqMap) {
        List<CarListBean> carsListExport = ownerDao.carsListExport(reqMap);
        return carsListExport;
    }

    @Override
    public String getServerName(Map<String, Object> reqMap) {
        String serverName = ownerDao.getServerName(reqMap);
        return serverName;
    }

    //通过车主id逻辑删除owner表中车主与车辆的关联
    @Override
    public void deleteCarByOwner(String id) {
        ownerDao.updateCarByOwner(id);
    }

	@Override
	public int applyAccountingPeriod(Map<String, Object> reqMap){
		int result = ownerDao.applyAccountingPeriod(reqMap);
		return result;
	}

	@Override
	public int addApplyAccountingPeriodRecord(Map<String, Object> reqMap){
		int result = ownerDao.addApplyAccountingPeriodRecord(reqMap);
		return result;
	}

	@Override
	public int selectApplyAccountingPeriod(Map<String, Object> reqMap){
		int count = ownerDao.selectApplyAccountingPeriod(reqMap);
		return count;
	}

	@Override
	public Map<String, Object> selectAccountingPeriodInfo(Map<String, Object> reqMap){
		return ownerDao.selectAccountingPeriodInfo(reqMap);
	}

	@Override
	public int updateAccountingPeriod(Map<String, Object> reqMap){
		int result = ownerDao.updateAccountingPeriod(reqMap);
		return result;
	}

	@Override
	public List<Map<String, Object>> selectApplyAccountingPeriodRecord(Map<String, Object> reqMap) {
		List<Map<String, Object>> list = ownerDao.selectApplyAccountingPeriodRecord(reqMap);
		return list;
	}


	@Override
	public void insertRepaymentStatement(Map<String, Object> reqMap) {
		ownerDao.insertRepaymentStatement(reqMap);
	}

	@Override
	public void deleteRepaymentStatement(Map<String, Object> reqMap) {
		ownerDao.deleteRepaymentStatement(reqMap);
	}

	@Override
	public List<Map<String, Object>> selectRepaymentStatement (Map<String, Object> reqMap) {
		List<Map<String, Object>> list = ownerDao.selectRepaymentStatement(reqMap);
		return list;
	}

	@Override
	public void updateRepaymentStatement(Map<String, Object> reqMap){
		ownerDao.updateRepaymentStatement(reqMap);
	}

	@Override
	public List<Map<String, Object>> selectAllNoRepaymentStatement () {
		List<Map<String, Object>> list = ownerDao.selectAllNoRepaymentStatement();
		return list;
	}

	@Override
	public List<Map<String, Object>> selectAllNoRepaymentStatementByDay(int day) {
		List<Map<String, Object>> list = ownerDao.selectAllNoRepaymentStatementByDay(day);
		return list;
	}

}
